const fs = require('fs');
const path = require('path');

class BattleLogger {
    constructor(battleId = 'default') {
        this.battleId = battleId;
        this.logDir = path.join(__dirname, '..', 'logs');
        this.logFile = path.join(this.logDir, `battle_server.log`);

        // 确保日志目录存在
        if (!fs.existsSync(this.logDir)) {
            fs.mkdirSync(this.logDir, { recursive: true });
        }

        // 初始化日志文件
        this.initLogFile();
    }

    initLogFile() {
        const timestamp = new Date().toISOString();
        const header = `\n=== Battle Server Log Started at ${timestamp} ===\n` +
                      `Battle ID: ${this.battleId}\n` +
                      `Process PID: ${process.pid}\n` +
                      `Node.js Version: ${process.version}\n` +
                      `=================================================\n\n`;

        fs.writeFileSync(this.logFile, header);
        console.log(`📝 Battle server log initialized: ${this.logFile}`);
    }

    formatTimestamp() {
        const now = new Date();
        return now.toISOString().replace('T', ' ').substring(0, 23);
    }

    writeLog(level, category, message, data = null) {
        const timestamp = this.formatTimestamp();
        const prefix = `[${timestamp}] [${level.toUpperCase()}] [${category}]`;

        let logMessage = `${prefix} ${message}`;

        if (data) {
            if (typeof data === 'object') {
                logMessage += `\n${JSON.stringify(data, null, 2)}`;
            } else {
                logMessage += ` ${data}`;
            }
        }

        logMessage += '\n';

        // 写入文件
        fs.appendFileSync(this.logFile, logMessage);

        // 同时输出到控制台
        console.log(`${prefix} ${message}`);
        if (data) {
            console.log(data);
        }
    }

    info(category, message, data = null) {
        this.writeLog('INFO', category, message, data);
    }

    warn(category, message, data = null) {
        this.writeLog('WARN', category, message, data);
    }

    error(category, message, data = null) {
        this.writeLog('ERROR', category, message, data);
    }

    debug(category, message, data = null) {
        this.writeLog('DEBUG', category, message, data);
    }

    // 专门用于记录战斗系统相关的日志
    battleSystem(message, data = null) {
        this.info('BATTLE_SYSTEM', message, data);
    }

    // 专门用于记录命令执行的日志
    command(message, data = null) {
        this.info('COMMAND', message, data);
    }

    // 专门用于记录回合执行的日志
    round(message, data = null) {
        this.info('ROUND', message, data);
    }

    // 专门用于记录性能相关的日志
    performance(message, data = null) {
        this.info('PERFORMANCE', message, data);
    }

    // 记录方法调用的开始和结束
    methodStart(methodName, params = null) {
        this.debug('METHOD', `🚀 ${methodName} - START`, params);
    }

    methodEnd(methodName, result = null, duration = null) {
        let message = `✅ ${methodName} - END`;
        if (duration !== null) {
            message += ` (${duration}ms)`;
        }
        this.debug('METHOD', message, result);
    }

    methodError(methodName, error, duration = null) {
        let message = `❌ ${methodName} - ERROR`;
        if (duration !== null) {
            message += ` (${duration}ms)`;
        }
        this.error('METHOD', message, {
            error: error.message,
            stack: error.stack
        });
    }

    // 专门用于记录回合开始和结束
    roundStart(roundNumber) {
        this.info('ROUND', `🚀 开始执行回合 ${roundNumber}`, {
            round: roundNumber,
            timestamp: new Date().toISOString()
        });
    }

    roundEnd(roundNumber, duration = null) {
        let message = `✅ 回合 ${roundNumber} 执行完成`;
        if (duration !== null) {
            message += ` (${duration}ms)`;
        }
        this.info('ROUND', message);
    }

    roundError(roundNumber, error, duration = null) {
        let message = `❌ 回合 ${roundNumber} 执行失败`;
        if (duration !== null) {
            message += ` (${duration}ms)`;
        }
        this.error('ROUND', message, {
            error: error.message,
            stack: error.stack
        });
    }

    // 专门用于记录战斗状态
    state(message, data = null) {
        this.info('STATE', message, data);
    }

    // 专门用于记录命令相关信息
    commands(message, commands = null) {
        this.info('COMMANDS', message, {
            count: commands ? commands.length : 0,
            commands: commands
        });
    }

    commandResult(message, result = null, duration = null) {
        let logMessage = message;
        if (duration !== null) {
            logMessage += ` (${duration}ms)`;
        }
        this.info('COMMAND_RESULT', logMessage, result);
    }

    // 清理日志文件（保留最近的日志）
    cleanup(maxFiles = 10) {
        try {
            const files = fs.readdirSync(this.logDir)
                .filter(file => file.startsWith('battle_server_') && file.endsWith('.log'))
                .map(file => ({
                    name: file,
                    path: path.join(this.logDir, file),
                    mtime: fs.statSync(path.join(this.logDir, file)).mtime
                }))
                .sort((a, b) => b.mtime - a.mtime);

            if (files.length > maxFiles) {
                const filesToDelete = files.slice(maxFiles);
                filesToDelete.forEach(file => {
                    fs.unlinkSync(file.path);
                    console.log(`🗑️ Deleted old log file: ${file.name}`);
                });
            }
        } catch (error) {
            console.error('Failed to cleanup log files:', error);
        }
    }
}

// 创建全局日志实例
let globalLogger = null;

function getLogger(battleId) {
    if (!globalLogger) {
        globalLogger = new BattleLogger(battleId);
    }
    return globalLogger;
}

module.exports = {
    BattleLogger,
    getLogger
};